LINQ - Simple Lambdas


LINQ
LINQ, Data Access
Desktop, Data
en-US
6/28/2011

Introduction

Several examples of how to write and use lambda expressions.

Building the Sample

Press F5

Description

This sample provides a brief introduction to the use of lambda expressions.

There are ten samples in this project. By default, the first sample will run. By changing the Main() method in Program.vb, you can modify the code to run one of the other samples. For instance, by default, Main makes the following call:

 
        Samples.Sample1()

Modify this code as follows to call Sample2():

        Samples.Sample2()

The samples are named Sample1(), Sample2(), and so forth, up to Sample10().

Screenshot

Sample Code

C#
Edit|Remove
    public static void Sample10() { 
        // use query expressions to simplify 
        var q = from p in persons  
                orderby p.Level, p.Name 
                group p.Name by p.Level into g 
                select new {Level = g.Key, Persons = g}; 
         
        foreach(var g in q) { 
            Console.WriteLine("Level: {0}", g.Level); 
            foreach(var p in g.Persons) { 
                Console.WriteLine("Person: {0}", p); 
            } 
        }                 
    }

Visual Basic
Edit|Remove
    Public Shared Sub Sample1() 
        ' use Where() to filter out elements matching a particular condition        
        Dim fnums = numbers.Where(Function(n) n < 5) 
 
        Console.WriteLine("Numbers < 5") 
        For Each x As Integer In fnums 
            Console.WriteLine(x) 
        Next 
    End Sub 
 
    Public Shared Sub Sample2() 
        ' use First() to find the one element matching a particular condition        
        Dim v As String = strings.First(Function(s) s(0) = "o"c) 
 
        Console.WriteLine("string starting with 'o': {0}", v) 
    End Sub 
 
    Public Shared Sub Sample3() 
        ' use Select() to convert each element into a new value 
        Dim snums = numbers.Select(Function(n) strings(n)) 
 
        Console.WriteLine("Numbers") 
        For Each s As String In snums 
            Console.WriteLine(s) 
        Next 
    End Sub

Source Code Files

More Information

For more information on LINQ: http://msdn.microsoft.com/en-us/netframework/aa904594.aspx